import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/gate_equipment_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/gate_plan_view_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/gate_region_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_tree_entity.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/task_closure/common/access_control_widget.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/task_closure/common/figure_shadow_widget.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/task_closure/common/regional_authorization_widget.dart';
import 'package:flutter/cupertino.dart';

/// 区域门禁授权弹窗页面
class AccessControlDialog extends StatefulWidget {
  const AccessControlDialog({required this.callback, required this.reservationType, super.key});

  /// 点击回调
  final Function(Map<String, dynamic>) callback;

  /// 预约类型 0：人员 1：普通车辆 2：危化车辆
  final int reservationType;

  @override
  State<AccessControlDialog> createState() => _AccessControlDialogState();
}

class _AccessControlDialogState extends State<AccessControlDialog> {
  /// 当前所处状态
  /// 0:区域授权 1:门禁授权 2:企业图引
  int type = 0;

  /// 选中的区域
  List<GateRegionEntity> selectedRegion = [];

  /// 选中的门禁
  List<GateEquipmentEntity> selectedAccessControl = [];

  /// 选中的图影
  List<GatePlanViewEntity> selectedFigureShadow = [];

  /// 是否检查
  bool isInspect = false;

  /// 封闭化-业务部门列表
  List<DepartmentTreeEntity> departments = [];

  /// 选中的部门列表
  List<DepartmentTreeEntity> selectedDepartment = [];

  @override
  void initState() {
    super.initState();
    // 类型为危化车辆时,才获取部门列表
    if (widget.reservationType == 2) {
      getDepartments();
    }
  }

  /// 获取封闭化部门列表
  /// 1：后台 2：特殊作业 3：双重预防机制 4：重大危险源 5：敏捷应急 6：安全教育培训 7：通用 8：智慧仓库 9：安全基础管理 10：封闭化 11：标准化 12：清单制
  Future<void> getDepartments() async {
    final resp = await HttpUtil().generateGetRequest<List<DepartmentTreeEntity>>(
      Interface.getBDepartment,
      queryParameters: {'type': '10'},
    ).execute();
    resp.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        departments.clear();
        departments.addAll(data);
      }
    });
  }

  /// 选择部门
  void showSelectDepartment() {
    CustomSelectFunction.selectMultipleBottomSheet<DepartmentTreeEntity>(
      onCallBack: (val) {
        selectedDepartment.clear();
        selectedDepartment.add(val.first);
        setState(() {});
      },
      dataList: departments,
      checkedList: selectedDepartment,
      isMultiple: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
      alignment: Alignment.topCenter,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20.w)),
        gradient: const LinearGradient(
            //渐变位置
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            //渐变颜色[始点颜色, 结束颜色]
            colors: [
              Color(0xffE7EAFF),
              Color(0xffffffff),
              Color(0xffffffff),
            ]),
      ),
      height: 530.w,
      child: Column(
        children: [
          Row(
            children: [
              Text(
                '区域门禁授权',
                style: TextStyle(color: Colors.black, fontSize: 18.sp, height: 1.2, fontWeight: FontWeight.bold),
              ),
              Text(
                '（多选）',
                style: TextStyle(color: const Color(0xffA2A2A2), fontSize: 14.sp, height: 1.2, fontWeight: FontWeight.bold),
              ),
              const Spacer(),
              IconButton(
                icon: Container(
                  width: 30.w,
                  height: 30.w,
                  decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(15.w))),
                  child: Icon(
                    Icons.close,
                    color: Colors.grey,
                    size: 21.w,
                  ),
                ),
                onPressed: () {
                  Navigator.pop(context);
                },
              )
            ],
          ),
          AppGaps.vGap12,
          // 进度栏
          _getScheduleView(),
          AppGaps.vGap16,
          Expanded(child: _getDataList()),
          Visibility(visible: widget.reservationType == 2, child: _getDepartmentView()),
          AppGaps.vGap6,
          // 下方按钮样式
          _getButtonView()
        ],
      ),
    ));
  }

  /// 获取位置进度样式
  Widget _getScheduleView() {
    return Row(
      children: [
        _getScheduleCurrentView(title: '①区域授权', isCurrent: type == 0),
        _getDivisionLine(),
        _getScheduleCurrentView(title: '②门禁授权', isCurrent: type == 1),
        _getDivisionLine(),
        _getScheduleCurrentView(title: '③企业图引', isCurrent: type == 2),
      ],
    );
  }

  /// 获取分割线
  Widget _getDivisionLine() {
    return Expanded(
        child: Container(
      color: const Color(0xff557CFD),
      height: 1.w,
    ));
  }

  /// 获取进度选中样式
  Widget _getScheduleCurrentView({String? title, bool isCurrent = false}) {
    return Container(
      alignment: Alignment.center,
      width: 100.w,
      height: 28.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(4.w)),
        gradient: LinearGradient(
          //渐变位置
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          //渐变颜色[始点颜色, 结束颜色]
          colors: isCurrent ? [const Color(0xff6E7DFF), const Color(0xff8E9AFF), const Color(0xff8E9AFF)] : [Colors.transparent, Colors.transparent],
        ),
      ),
      child: Text(
        title ?? '',
        style: TextStyle(
          color: isCurrent ? const Color(0xffffffff) : const Color(0xff495061),
          fontSize: 14.sp,
          height: 1.2,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  /// 数据列表
  Widget _getDataList() {
    switch (type) {
      case 0:
        return RegionalAuthorizationWidget(selectedRegion: selectedRegion);
      case 1:
        return AccessControlWidget(
          selectedRegion: selectedRegion,
          selectedAccessControl: selectedAccessControl,
          equipmentType: widget.reservationType == 0 ? '1' : '2',
        );
      default:
        return FigureShadowWidget(selectedFigureShadow: selectedFigureShadow);
    }
  }

  /// 获取危化车辆检查部门
  Widget _getDepartmentView() {
    return Column(
      children: [
        AppGaps.vGap12,
        Row(children: [
          Text(
            '是否检查',
            style: TextStyle(
              color: const Color(0xff495061),
              fontSize: 14.sp,
              height: 1.2,
              fontWeight: FontWeight.bold,
            ),
          ),
          AppGaps.hGap10,
          CupertinoSwitch(
            activeColor: const Color(0xFF5C6DFF),
            value: isInspect,
            onChanged: (value) {
              isInspect = !isInspect;
              selectedDepartment.clear();
              setState(() {});
            },
          ),
          AppGaps.hGap20,
          // 部门选择框
          Expanded(
            child: Visibility(
              visible: isInspect,
              child: Container(
                  padding: EdgeInsets.symmetric(vertical: 4.w, horizontal: 12.w),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: const Color(0xffffffff),
                      border: Border.all(color: const Color(0xff495061), width: 1.w),
                      borderRadius: BorderRadius.all(Radius.circular(6.w))),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          selectedDepartment.isEmpty ? '请选择部门' : selectedDepartment.first.getShowName(),
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 16.sp,
                            height: 1.2,
                            color: selectedDepartment.isEmpty ? const Color(0xff495061).withOpacity(0.6) : const Color(0xff495061),
                          ),
                        ),
                      ),
                      Icon(
                        Icons.keyboard_arrow_down_rounded,
                        size: 20.w,
                        color: const Color(0xff495061),
                      )
                    ],
                  )).clickOnce(showSelectDepartment),
            ),
          ),
        ])
      ],
    );
  }

  /// 下方按钮样式
  Widget _getButtonView() {
    return Row(
      children: [
        Visibility(
            visible: type != 0,
            child: Container(
                margin: EdgeInsets.only(right: 20.w),
                height: 40.w,
                width: 120.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: const Color(0xffffffff),
                    border: Border.all(color: const Color(0xff5C6DFF), width: 1.w),
                    borderRadius: BorderRadius.all(Radius.circular(20.w))),
                child: Text(
                  '上一步',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: const Color(0xff5C6DFF),
                  ),
                )).clickOnce(() {
              type--;
              setState(() {});
            })),
        Expanded(
          child: Container(
              height: 40.w,
              alignment: Alignment.center,
              decoration: BoxDecoration(color: const Color(0xff5C6DFF), borderRadius: BorderRadius.all(Radius.circular(20.w))),
              child: Text(
                type == 2 ? '确定' : '下一步',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: const Color(0xffffffff),
                ),
              )).clickOnce(() {
            // 区域
            if (type == 0 && selectedRegion.isEmpty) {
              AppToast.showWarning('请选择区域!');
              return;
            }
            // 门禁
            if (type == 1 && selectedAccessControl.isEmpty) {
              AppToast.showWarning('请选择门禁!');
              return;
            }
            if (type != 2) {
              type++;
              setState(() {});
            } else {
              // type=2 时为确认按钮
              if (isInspect && selectedDepartment.isEmpty) {
                AppToast.showWarning('请选择部门!');
                return;
              }
              Get.back();
              widget.callback({
                'selectedRegion': selectedRegion,
                'selectedAccessControl': selectedAccessControl,
                'selectedFigureShadow': selectedFigureShadow,
                'selectedDepartment': selectedDepartment,
              });
            }
          }),
        )
      ],
    );
  }
}
